<?php


namespace app\admin\controller;


use app\admin\model\ArchivesDeceasedModel;
use app\admin\model\CustomerInfoModel;
use app\admin\model\OrderDepositModel;
use app\admin\model\OrderModel;
use app\admin\model\OrderPayLogModel;
use cmf\controller\AdminBaseController;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use app\admin\model\ContractModel;

class DepositController extends  AdminBaseController
{

    /**
     *  格位信息
     * @return mixed|void
     */
    public function tomb_deposit(){
        if ($this->request->isPost()) {
            $parem = $this->request->param();
            $insert_order = $parem['order'];
            $insert_order['archives_sn'] = date('Ymdhis');
            $insert_order['closing_time'] = time();
            $insert_order['add_time'] = strtotime($parem['add_time']);
            $insert_order['handle'] = cmf_get_current_admin_id();
            $insert_order['deposit_time']  = strtotime($parem['add_time']);


            if ($insert_order['order_id']){
                $order_id = $insert_order['order_id'];
                unset($insert_order['order_id']);
                Db::name('order')->where(['order_id'=>$order_id])->update($insert_order);
            }else{
                $insert_order['tomb_typei']=1;
                $order_id = Db::name('order')->insertGetId($insert_order);
            }
            if ($order_id){
                return $this->success('提交成功',url("deposit_applyer",['order_id'=>$order_id]));
            }else{
                $this->error('提交失败',url("tomb_deposit",['order_id'=>$order_id]));
            }
        }
        $parem = $this->request->param();

        $tomb_id =  isset($parem['tomb_id'])?$parem['tomb_id']:'';
        $order_id = isset($parem['order_id'])?$parem['order_id']:'';
        if ($order_id){
            $tomb_info = Db::name("order")->alias("o")
                ->join("tombarea_row_col c","o.tomb_id = c.colID ","left")
                ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
                ->whereIn('o.order_id',$order_id)->find();
            $tomb_id = $tomb_info['tomb_id'];
            $tomb_info['shoppingguide_name'] = cmf_get_admin_name($tomb_info['shoppingguide']);
            $tomb_info['handle'] = cmf_get_admin_name($tomb_info['handle']);
            $tomb_info['agent_user'] = cmf_get_admin_name($tomb_info['agent_user']);
        }else{
            $tomb_info = Db::name("tombarea_row_col")->alias("c")
                ->join("dj_tombarea_information_product p","c.colID = p.tomb_id","left")
                ->whereIn('c.colID',$tomb_id)->find();

            $tomb_info['shoppingguide_name'] = cmf_get_admin_name();
            $tomb_info['shoppingguide'] = cmf_get_current_admin_id();
            $tomb_info['handle'] = cmf_get_admin_name();
            $tomb_info['agent_user'] = cmf_get_admin_name();
        }

        $tomb_infos = Db::name("tombarea_row_col")->alias("c")
            ->join("dj_tombarea_row tr","c.rowid = tr.rowID","left")
            ->join("dj_tombarea t","tr.tombarea_id = t.id","left")
            ->field('tr.column row_column,tr.tombarea_id,t.name tombarea_name,t.cemetery_id')
            ->whereIn('c.colID',$tomb_id)->find();


        $cemetery_id =  $this->getParent($tomb_infos['cemetery_id']);

        // 只查代理商的人員
        $dailishang_list = Db::name("user")->alias('u')->field('u.*,d.department_name')
            ->join('dj_department d', 'd.id=u.dept_id')
            ->where("d.dept_type","8")
            ->order('d.department_name', 'DESC')
            ->select();

        $user = Db::name("user")->alias('u')->field('u.*,d.department_name')
            ->join('dj_department d', 'd.id=u.dept_id')
            ->order('d.department_name', 'DESC')
            ->select();
        $tomb_info['row_column'] =$tomb_infos['row_column'];
        $tomb_info['weizhi'] =$cemetery_id;
        $result_deposit_cost = Db::name("Costset")->where('id', 1)->find();

        $queue_convergence = config('queue.convergence');
        $this->assign('tomb_convergence',$queue_convergence);
        $this->assign([
            'order_id'=>$order_id,
            'deposit_cost'=>$result_deposit_cost['deposit_cost'],
            'tomb_convergence'=>$queue_convergence,
            'cate_id'=>4,
            'num_sn'=>$tomb_info['num'],
            'col_id'=>$tomb_id,
            'cate_name'=>$this->cate_arr[4],
            'admin_name'=> cmf_get_admin_name(),
            'user_list'=>$user,
            'handle'=>'',
            'dailishang_list'=>$dailishang_list,
        ]);

        $tomb_info['tomb_status'] = $this->col_status[$tomb_info['col_status']];
        $tomb_info['add_order_time'] = date('Y-m-d H:i',time());

        $this->assign('result',$tomb_info);
        return $this->fetch();
    }

    /**
     *  申请人
     * @return mixed
     */
    public function deposit_applyer(){
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!idcard_verify_number($data['customer_account'])){
                return $this->error('证件号格式不正确');
            }
            $validate=validate("CustomerInfo");
            if(!$validate->scene("save")->check($data)){
                return $this->error($validate->getError());//内置错误返回
            }

            $customer_id = $data['customer_id'];
            $order_id = $data['order_id'];
            unset($data['customer_id']);
            unset($data['order_id']);
            $data['add_time'] = time();
            if ($customer_id){
                CustomerInfoModel::update($data,['id'=>$customer_id]);
            }else{
                $data['add_user'] = cmf_get_current_admin_id();
                $customer_id = Db::name("customer_info")->insertGetId($data);
            }
            if ($customer_id){
                $con_is = Db::name('contract')->where(['order_id'=>$order_id])->find();
                OrderModel::update(['customer_id' => $customer_id],['order_id'=>$order_id]);

                if (!$con_is){
                    $contract_sn = ContractModel::get_contract_sn();
                    $count =Db::name('contract')->order('contract_id DESC')->find();
                    $file =  ContractModel::content_temp($order_id,$contract_sn);
                    Db::name('contract')->insertGetId(['order_id'=>$order_id,'contract_sn'=>$contract_sn,
                        'contract_file'=>json_encode($file),'keep_record_time'=>time(),'add_time'=>time(),'customer_id' => $customer_id]);
                }
                $this->success("保存成功", url("deposit_user", ['customer_id' => $customer_id,'order_id'=>$order_id]));

            }else{
                $this->error('添加客户失败');
            }
        }
        $data = $this->request->param();
        $order_info = Db::name("order")->where(['order_id'=>$data['order_id']])->find();
        $result_info = Db::name("customer_info")->where(['id'=>$order_info['customer_id']])->find();
//
        $result_info['shoppingguide'] = cmf_get_admin_name(isset($result_info['shoppingguide'])?$result_info['shoppingguide']:'');
        $this->assign([
            'order_id'=>$data['order_id'],
            'result'=>$result_info,
            'tomb_num'=>$order_info['tomb_num'],
            'tomb_type_name'=>$this->cate_arr[$order_info['tomb_type']],
        ]);
        return $this->fetch();
    }

    /**
     *  寄存信息
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deposit_user(){
        if ($this->request->isPost()) {
            $param = $this->request->param();

            $validate=validate("ArchivesDeceased");
            $result = $validate->scene("add_jc")->check($param);
            if ($result !== true) {
                return $this->error($result);
            }
            $deceased_id = $param['deceased_id'];

            //档案管理-逝者信息表
            $data['type'] = 2;
            $data['deceased_name'] = $param['deceased_name'];
            $data['gender'] = $param['gender'];
            $data['date_birth'] = $param['date_birth'];
            $data['date_death'] = $param['date_death'];
            $data['cremation_certificate_file_id'] = isset($param['cremation_certificate_file_id'])?$param['cremation_certificate_file_id']:'';
            $data['cremation_certificate'] = isset($param['cremation_certificate'])?$param['cremation_certificate']:'';
            $data['relationship_users'] = $param['relationship_users'];
            $data['convergence_type'] = $param['convergence_type'];
            $data['customer_id'] = $param['customer_id'];
            $data['tomb_id'] = $param['tomb_id'];
            $data['tomb_num'] = $param['tomb_num'];
            $data['order_id'] = $param['order_id'];
            $data['cate'] = 4;
            $data['add_time'] = time();
            if (!empty($deceased_id)){
                ArchivesDeceasedModel::update($data,['deceased_id'=>$deceased_id]);
                $result_id = $deceased_id;
            }else{
                $result_id = Db::name('archives_deceased')->strict(false)->insertGetId($data);
            }
            return $this->success("添加成功",url("Deposit/signcontract",['order_id'=>$param['order_id'],'deceased_id'=>$result_id]));
        }
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_info = Db::name('order')->alias('o')->field('o.tomb_id,o.tomb_num,o.tomb_type,p.tomb_regulation,o.customer_id')
            ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
            ->where(['o.order_id'=>$order_id])->find();
        $customer_id = $order_info['customer_id'];
        $result_list = Db::name('archives_deceased')->where(['order_id'=>$order_id])->find();

        if ($result_list){
            $result_list['gender1'] =  $result_list['gender']==1?"selected":'';
            $result_list['gender2'] =  $result_list['gender']==2?"selected":'';
//            $result_list['date_birth'] = $result_list['date_birth'];
//            $result_list['date_death'] =$result_list['date_death'];
            $result_list['cremation_certificates'] = '/upload/'.$result_list['cremation_certificate'];
        }

        $this->assign([
            'tomb_type_name'=>$this->cate_arr[$order_info['tomb_type']],
            'tomb_regulation'=>$order_info['tomb_regulation'],
            'tomb_id'=>$order_info['tomb_id'],
            'tomb_num'=>$order_info['tomb_num'],
            'order_id'=>$data['order_id'],
            'result_list'=>$result_list,
            'customer_id'=>$customer_id,
        ]);
        return $this->fetch();
    }

    /**
     *  合同签订
     * @return mixed
     */
    public function signcontract(){
        if ($this->request->isPost()){
            $param = $this->request->param();

            if (!empty(session('sign_time'))) {
                session('sign_time',$param['sign_time']);
                if (empty($param['contract_enclosure'])){
                    return $this->error('上传签章合同');
                }else{
                    session('sign_time','');
                }
            }

            $result_order = Db::name('order')->where(['order_id'=>$param['order_id']])->find();
            $insert = [
                'tomb_type'=>$result_order['tomb_type'],
                'tomb_id'=>$result_order['tomb_id'],
                'contract_enclosure'=>$param['contract_enclosure'],
                'contract_enclosure_file_id'=>$param['contract_enclosure_file_id'],
                'supplement'=>$param['supplement'],
                'supplement_file_id'=>$param['supplement_file_id'],
                'keep_record_time'=>strtotime($param['keep_record_time']),
                'sign_time'=>strtotime($param['sign_time']),
                'add_time'=>time(),
            ];
            Db::name('contract')->where(['contract_sn'=>$param['contract_sn']])->update($insert);
            OrderModel::update(['contract_sn'=>$param['contract_sn'],'sign_time'=>strtotime($param['sign_time']),'dz_time'=>strtotime($param['sign_time']),'sj_time'=>strtotime($param['sign_time'])],['order_id'=>$param['order_id']]);
            ContractModel::content_temp($param['order_id'],$param['contract_sn'],strtotime($param['sign_time']));

            return $this->success('提交成功');
//            $this->success('提交成功',url('Orderpay',['order_id'=>$param['order_id']]));
        }
        $data = $this->request->param();
        $order_id = $data['order_id'];

        $result = Db::name('contract')->alias('c')
            ->leftJoin('dj_asset f','c.contract_enclosure_file_id  = f.id')
            ->leftJoin('dj_asset ff','c.supplement_file_id  = ff.id')
            ->field('c.*,f.filename contract_enclosure_file_name,ff.filename supplement_file_name')
            ->where(['order_id'=>$order_id])->find();


        $contract_sn = $result['contract_sn'];
       $file = json_decode($result['contract_file'],true);
        $keep_record_time =  date('Y-m-d H:i',$result['keep_record_time']);
//        $file =  ContractModel::content_temp($data['order_id'],$contract_sn);

        $order_info = Db::name("order")->where(['order_id'=>$data['order_id']])->find();
        $site_domain = cmf_get_domain().'/';
        $sign_time =  date('Y-m-d H:i',$result['sign_time']?$result['sign_time']:time());
        $this->assign("add_order_time",$keep_record_time);
        $this->assign("order_id", $data['order_id']);
        $this->assign([
            'result'=>$result,
            'contract_sn'=>$contract_sn,
            'file'=>$file,
            'customer_id'=>$order_info['customer_id'],
            'tomb_num'=>$order_info['tomb_num'],
            'json_file'=>json_encode($file),
            'sign_time'=>$sign_time,
            'file_html'=>$site_domain.cmf_get_image_preview_url($file['html']),
            'file_docx'=>$site_domain.cmf_get_image_preview_url($file['doc'])
        ]);
        return $this->fetch();
    }

    public function orderpay($ajax=0){
        if ($this->request->isPost()){
            $data=$this->request->param();
            if (empty($data['real_name'])){
                $this->error('请填写付款人姓名');
            }

            if (empty($data['real_phone'])){
                $this->error('请填写付款人联系方式');
            }
            if (!cmf_check_mobile($data['real_phone'])){
                $this->error('请填写付款人手机号错误！');
            }

            $DepositModel = new OrderDepositModel();
            $res = $DepositModel->doAddData($data);

            if ($res){
                return $this->success('提交成功',url('orders/visua'));
            }else{
                return  $this->error($DepositModel->getError());
            }
        }
        $data = $this->request->param();
        $order_id =  $data['order_id'];
        $is_ht =  Db::name('contract')->where(['order_id'=>$order_id])->find();
        if ($ajax==1){
            if (empty($is_ht['contract_enclosure'])){
                return $this->error('请上传完签章合同后先保存，再点击下一步');
            }
//            if (empty($is_ht['supplement'])){
//                return $this->error('请上传上传合同附件！请先保存');
//            }
            return $this->success('');
        }
        $field ="o.*";
        $field.=",p.tomb_regulation,p.tomb_region,p.tomb_address";
        $field.=",c.col_status pro_status,c.reacher";
        $result_order = Db::name('order')->alias('o')->field($field)
//            ->field('o.contract_sn,o.tomb_num,o.closing_price,'o.*,p.*,c.reacher'
//            p.pro_status,p.tomb_regulation,p.tomb_region,p.tomb_address,p.layer_num,p.tomb_bit_number,
//            o.customer_id,o.shoppingguide,o.add_time,o.tomb_type')

            ->join("dj_tombarea_row_col c","o.tomb_id = c.colID")
            ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
            ->where(['o.order_id'=>$order_id])->find();

        $result_order['tomb_regulation'] = $this->regulation_arr[$result_order['tomb_regulation']];
        $result_order['pro_status'] = $this->col_status[$result_order['pro_status']];
        $result_order['add_time'] = date('Y-m-d H:i:s',$result_order['add_time']);//$result_order['pro_status']];
        $result_order['tomb_type'] = $this->cate_arr[$result_order['tomb_type']];

        $result_customer = Db::name('customer_info')->where('id',$result_order['customer_id'])->find();
        $result_deposit = Db::name('pay_deposit')->where('order_id',$order_id)->select();
        $result_goods = Db::name('order_goods')->where('order_id',$order_id)->select();
        $goods=[];
        $goods_total_price=0;

        $result_order['discount_price']  = intval($result_order['discount_price']);
        $result_order['shoppingguide_name']  = cmf_get_admin_name($result_order['shoppingguide']);
        $result_order['agent_user_name']  = cmf_get_admin_name($result_order['agent_user']);
        $result_order['handle_name']  = cmf_get_admin_name($result_order['handle']);
        $result_order['payaddtime']  = date('Y-m-d H:i:s',time());


        $this->assign([
            'result'=>$result_order,
            'customer'=>$result_customer,
            'deposit'=>$result_deposit,
            'goods_arr'=>$goods,
            'order_id'=>$order_id,
            'goods_total_price'=>$goods_total_price,
        ]);

        return $this->fetch();
    }



    public  function getParent( $pid ,$array=[],$info_arr=[]) {
        static $level = 1;
        $is_parent = Db::name( 'cemetery')->where(["id"=>$pid])->find();
        $info_arr['name_'.$level] = $is_parent['name'];
        $array[] = $is_parent;
        if ( $is_parent["parent_id"] ) {
            $level++;
            return $this->getParent( $is_parent['parent_id'],$array,$info_arr);
        }
        return $info_arr;
    }


    /**
     *  合同文件
     * @param $order_id
     * @param $contract_sn
     * @return array
     */
    public function content_temp($order_id,$contract_sn){

        $field = 'o.*,p.*,c.rows_num,column_num';
        $result_order = Db::name('order')->alias('o')->field($field)
            ->join("dj_tombarea_row_col c","o.tomb_id = c.colID","left")
            ->join("dj_tombarea_information_product p","o.tomb_product_id = p.id","left")
            ->where(['o.order_id'=>$order_id])->find();
        $customer_info = Db::name("customer_info")->where(['id'=>$result_order['customer_id']])->find();

        $tomb_region = ContractModel::getSupName($result_order['cemetery_id']);
        $tomb_region_ceng='';
        $tomb_region_qu='';
        $tomb_region_yuan='';
        foreach ($tomb_region as $k=>&$v){
            if ($v['type']=='层') {
                $tomb_region_ceng = $v['name'];
            }elseif ($v['type']=='区'){
                $tomb_region_qu = $v['name'];
            }elseif ($v['type']=='园'){
                $tomb_region_yuan = $v['name'];
            }else{
                $region = '';
            }
        }


        $templateProcessor = new TemplateProcessor('document/合同类/寄存协议/骨灰寄存协议.docx');

        $templateProcessor->setValue('customer_buyer_name',$customer_info['buyer_name']); //
        $templateProcessor->setValue('customer_buyer_phone',$customer_info['buyer_phone']); //
        $templateProcessor->setValue('customer_customer_account',$customer_info['customer_account']); //
        $templateProcessor->setValue('customer_customer_address',$customer_info['customer_address']); //

        $templateProcessor->setValue('tomb_region_qu',$tomb_region_qu);//所在区域
        $templateProcessor->setValue('tomb_region_yuan',$tomb_region_yuan);//所在区域
        $templateProcessor->setValue('tomb_region_ceng',$tomb_region_ceng?$tomb_region_ceng:$result_order['layer_num']);//所在区域
        $templateProcessor->setValue('row_num',$result_order['rows_num']);  //排
        $templateProcessor->setValue('tomb_bit_number',$result_order['column_num']);  // 位
        $templateProcessor->setValue('tomb_num',$result_order['tomb_num']);  // 墓位编号

        $templateProcessor->setValue('closing_price',$result_order['closing_price']); // 总计
        $templateProcessor->setValue('closing_price_num',number2chinese($result_order['closing_price'],false)); // 总计

        $templateProcessor->setValue('year',date('Y')); // 年
        $templateProcessor->setValue('month',date('m')); // 月
        $templateProcessor->setValue('day',date('d')); // 日

        $file = 'document/file/contract/'.$contract_sn;

//        $file = 'temp/doc/'.$contract_sn.'-'.$result_order['tomb_num'].'';
        $templateProcessor->saveAs($file.'.docx');
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($file.'.docx');
        $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
        $xmlWriter ->save($file.'.html');
        return ['doc'=>$file.'.docx','html'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$file.'.html'];
    }

}